// band_withdrawal_edit_page.dart
import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:sjx/repository/model/withdrawal_model.dart';
import 'package:sjx/utils/sp_utils.dart';
import 'package:sjx/repository/model/user_model.dart';

import '../../repository/sjx_api.dart';

class BandWithdrawalEditPage extends StatefulWidget {
  final WithdrawalModel? withdrawalModel;
  final VoidCallback onUpdate;

  const BandWithdrawalEditPage({
    super.key,
    this.withdrawalModel,
    required this.onUpdate,
  });

  @override
  State<BandWithdrawalEditPage> createState() => _BandWithdrawalEditPageState();
}

class _BandWithdrawalEditPageState extends State<BandWithdrawalEditPage> {
  final TextEditingController _accountController = TextEditingController();
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();

  bool _isLoading = false;
  bool _isCodeSending = false;
  int _countdown = 0;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    // 初始化表单数据
    if (widget.withdrawalModel != null) {
      _accountController.text = widget.withdrawalModel!.account ?? '';
      _nameController.text = widget.withdrawalModel!.realName ?? '';
    }
  }

  @override
  void dispose() {
    _accountController.dispose();
    _nameController.dispose();
    _codeController.dispose();
    _timer?.cancel();
    super.dispose();
  }

  void _startCountdown() {
    _countdown = 60;
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdown > 0) {
          _countdown--;
        } else {
          _timer?.cancel();
        }
      });
    });
  }

  Future<void> _sendVerificationCode() async {
    try {
      setState(() {
        _isCodeSending = true;
      });

      final user = await SpUtils.getUserData();
      await SJXApi.instance().phoneCode(user!.mobile);

      _startCountdown();
      _showMessage('验证码已发送');
    } catch (e) {
      _showMessage('发送失败: $e');
    } finally {
      setState(() {
        _isCodeSending = false;
      });
    }
  }

  Future<void> _submitForm() async {
    if (_accountController.text.isEmpty) {
      _showMessage('请输入支付宝账号');
      return;
    }

    if (_nameController.text.isEmpty) {
      _showMessage('请输入支付宝真实姓名');
      return;
    }

    if (_codeController.text.isEmpty) {
      _showMessage('请输入验证码');
      return;
    }

    try {
      setState(() {
        _isLoading = true;
      });

      final user = await SpUtils.getUserData();
      if (user == null) {
        _showMessage('用户未登录');
        return;
      }


      await SJXApi.instance().verifySmsCode(user.mobile, _codeController.text.trim());
      await SJXApi.instance().bandAlipayAccountInfo({"aliPayName": _nameController.text, "aliPayAccount": _accountController.text});

      _showMessage('绑定成功');

      // 回调更新
      widget.onUpdate();
      await Future.delayed(const Duration(milliseconds: 1500));
      if (mounted) {
        Navigator.of(context).pop();
      }
    } on DioException catch (e) {
      setState(() {
        _isLoading = false;
      });
    } catch (e) {
      _showMessage('绑定失败: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _showMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('绑定账户'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      backgroundColor: const Color.fromRGBO(244, 247, 250, 1),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            // 表单卡片
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 4,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Column(
                children: [
                  // 支付宝账号
                  _buildFormItem(
                    label: '支付宝账号',
                    controller: _accountController,
                    hintText: '请输入支付宝账号',
                    isFirst: true,
                  ),
                  const Divider(height: 1, indent: 15),
                  // 姓名
                  _buildFormItem(
                    label: '姓名',
                    controller: _nameController,
                    hintText: '请输入收款支付宝账户人的姓名',
                  ),
                  const Divider(height: 1, indent: 15),
                  // 验证码
                  _buildVerificationCodeItem(),
                ],
              ),
            ),

            const SizedBox(height: 12),

            // 提示信息
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: const Color(0xFFFFF2E8),
                borderRadius: BorderRadius.circular(6),
                border: Border.all(
                  color: const Color(0xFFFFBB96),
                  width: 1,
                ),
              ),
              child: const Text(
                '* 支付宝账户和姓名必须为真实信息，且一致',
                style: TextStyle(
                  fontSize: 12,
                  color: Color(0xFFFA541C),
                ),
              ),
            ),

            const SizedBox(height: 24),

            // 确定按钮
            SizedBox(
              width: double.infinity,
              height: 44,
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: Theme.of(context).colorScheme.primary,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(22),
                  ),
                  elevation: 0,
                ),
                onPressed: _isLoading ? null : _submitForm,
                child: _isLoading
                    ? const SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation(Colors.white),
                  ),
                )
                    : const Text(
                  '确定',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildFormItem({
    required String label,
    required TextEditingController controller,
    required String hintText,
    bool isFirst = false,
  }) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            width: 90,
            child: Text(
              label,
              style: const TextStyle(
                fontSize: 16,
                color: Color(0xFF262626),
              ),
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: TextField(
              controller: controller,
              decoration: InputDecoration(
                border: InputBorder.none,
                hintText: hintText,
                hintStyle: const TextStyle(
                  color: Color(0xFFBFBFBF),
                  fontSize: 14,
                ),
                contentPadding: EdgeInsets.zero,
              ),
              style: const TextStyle(
                fontSize: 14,
                color: Color(0xFF262626),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildVerificationCodeItem() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const SizedBox(
            width: 90,
            child: Text(
              '验证码',
              style: TextStyle(
                fontSize: 16,
                color: Color(0xFF262626),
              ),
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: TextField(
              controller: _codeController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                border: InputBorder.none,
                hintText: '请输入验证码',
                hintStyle: TextStyle(
                  color: Color(0xFFBFBFBF),
                  fontSize: 14,
                ),
                contentPadding: EdgeInsets.zero,
              ),
              style: const TextStyle(
                fontSize: 14,
                color: Color(0xFF262626),
              ),
            ),
          ),
          const SizedBox(width: 16),
          SizedBox(
            width: 88,
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: _countdown > 0
                    ? Colors.grey.shade300
                    : Theme.of(context).colorScheme.primary,
                foregroundColor: _countdown > 0 ? Colors.grey : Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(4),
                ),
                padding: const EdgeInsets.symmetric(vertical: 8),
                elevation: 0,
              ),
              onPressed: (_isCodeSending || _countdown > 0)
                  ? null
                  : _sendVerificationCode,
              child: _isCodeSending
                  ? const SizedBox(
                width: 16,
                height: 16,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation(Colors.white),
                ),
              )
                  : Text(
                _countdown > 0 ? '已发送($_countdown)' : '获取验证码',
                style: TextStyle(
                  fontSize: 12,
                  color: _countdown > 0
                      ? Colors.grey
                      : Colors.white,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}